<template>
  <header-comp :simulation-time="serverMsg.timestamp"></header-comp>
  <mini-container-to-enemy :message-data = this.messageData :show-mini-container-to-enemy-div = this.switches.showMiniContainerToEnemyDiv  v-show="switches.showMiniContainerToEnemyDiv" ></mini-container-to-enemy>
  <mini-container-to-us :message-data = this.messageData  v-show="switches.showMiniContainerToUsDiv" ></mini-container-to-us>
  <div class="switchButton" v-show="switches.showSwitchButtonDiv">
    <div style="color: #6adae8; font-size: medium; text-align: center; padding-top: 5px">控制台</div>
    <el-descriptions :column="2" style="font-size: small; margin-bottom: 5px">
      <el-descriptions-item label="阶段名称">{{ serverMsg.stageName }}</el-descriptions-item>
      <el-descriptions-item label="任务编号">{{ serverMsg.taskCode }}</el-descriptions-item>
      <el-descriptions-item label="任务类型">{{ serverMsg.taskType }}</el-descriptions-item>
      <el-descriptions-item label="倍率">{{ serverMsg.rate }}</el-descriptions-item>
    </el-descriptions>
    <el-row style="padding-left: 20px; padding-top: 20px">
      <el-col :span="6">
        轨道
        <el-switch v-model="switches.showOrbit" active-color="#6adae8" inactive-color="#060c1e" @change="switchOrbit" />
      </el-col>
    </el-row>
    <el-row style="padding-left: 20px; padding-top: 20px">
      <el-col :span="6">
        名称
        <el-switch v-model="switches.showName" active-color="#6adae8" inactive-color="#060c1e" @change="switchName" />
      </el-col>
      <el-col :span="6">
        规避
        <el-switch @change="avoid" v-model="isAvoid" active-color="#6adae8" inactive-color="#060c1e"/>
      </el-col>
    </el-row>
    <el-row style="padding-left: 20px; padding-top: 20px"> </el-row>
    <div class="targetSelect">
      <el-radio-group v-model="cameraType" @change="changeCameraType">
        <el-radio label="自由视角"></el-radio>
        <el-radio label="我方卫星"></el-radio>
        <el-radio label="敌方卫星"  v-show="'DN' !== this.serverMsg.taskType"></el-radio>
        <el-radio label="导弹" v-show="'DN' === this.serverMsg.taskType"></el-radio>
      </el-radio-group>
      <div style="margin-top: 20px; color: white">
        速率调整
        <el-input-number v-model="rate" @change="handleChangeRate" :min="1" :max="1000" label="速率调整"></el-input-number>
      </div>
    </div>
  </div>

  <div v-show="switches.showDetail">
    <div class="dfWeixinStatus"  v-show="switches.showEnemyStatus">
      <div style="color: #6adae8; font-size: medium; text-align: center; padding-top: 5px">敌方卫星状态信息</div>
      <el-descriptions :column="2" style="font-size: small; margin-bottom: 5px;">
        <el-descriptions-item label="当前位置">{{ serverMsg.showText.enemyStatus.Position_J2000 }}</el-descriptions-item>
        <el-descriptions-item label="当前速度">{{ serverMsg.showText.enemyStatus.Velocity_J2000 }}</el-descriptions-item>
        <el-descriptions-item label="当前姿态四元数">{{ serverMsg.showText.enemyStatus.Quaternion }}</el-descriptions-item>
        <el-descriptions-item label="最近轨道机动时刻">{{ serverMsg.showText.enemyStatus.Last_orbital_maneuver_time
          }}</el-descriptions-item>
        <el-descriptions-item label="最近轨道机动ΔV消耗">{{ serverMsg.showText.enemyStatus.Last_orbital_maneuver_deltaV
          }}</el-descriptions-item>
        <el-descriptions-item label="累计ΔV消耗">{{ serverMsg.showText.enemyStatus.Accumulated_deltaV
          }}</el-descriptions-item>
        <el-descriptions-item label="剩余ΔV">{{ serverMsg.showText.enemyStatus.Remaining_deltaV
          }}</el-descriptions-item>
        <el-descriptions-item label="速度增量消耗">{{ serverMsg.showText.enemyStatus.Maneuver_deltaV_norm
          }}</el-descriptions-item>
      </el-descriptions>
    </div>
    <div class="dfWeixinFigthStatus" v-show="switches.showEnemyFigthDiv">
      <div style="color: #6adae8; font-size: medium; text-align: center; padding-top: 5px">敌方卫星作战效果</div>
      <el-descriptions :column="2" style="font-size: small; margin-bottom: 5px">
        <el-descriptions-item label="打击状态">{{ serverMsg.showText.enemyFigth.Strike_state }}</el-descriptions-item>
        <el-descriptions-item label="累计打击时长">{{ serverMsg.showText.enemyStatus.Accumulated_Strike_time
          }}</el-descriptions-item>
        <el-descriptions-item label="入射角">{{ serverMsg.showText.enemyStatus.Sun_angle }}</el-descriptions-item>
      </el-descriptions>
    </div>
    <div class="wfWeixinStatus" v-show="switches.showUsSattleInfoDiv">
      <div style="color: #6adae8; font-size: medium; text-align: center; padding-top: 5px">我方卫星状态信息</div>
      <el-descriptions :column="2" style="font-size: small; margin-bottom: 5px">
        <el-descriptions-item label="当前位置">{{ serverMsg.showText.usStatus.Position_J2000 }}</el-descriptions-item>
        <el-descriptions-item label="当前速度">{{ serverMsg.showText.usStatus.Velocity_J2000 }}</el-descriptions-item>
        <el-descriptions-item label="当前姿态四元数">{{ serverMsg.showText.usStatus.Quaternion }}</el-descriptions-item>
        <el-descriptions-item label="最近轨道机动时刻">{{ serverMsg.showText.usStatus.Last_orbital_maneuver_time
          }}</el-descriptions-item>
        <el-descriptions-item label="最近轨道机动ΔV消耗">{{ serverMsg.showText.usStatus.Last_orbital_maneuver_deltaV
          }}</el-descriptions-item>
        <el-descriptions-item label="累计ΔV消耗">{{ serverMsg.showText.usStatus.Accumulated_deltaV
          }}</el-descriptions-item>
        <el-descriptions-item label="剩余ΔV">{{ serverMsg.showText.usStatus.Remaining_deltaV }}</el-descriptions-item>
        <el-descriptions-item label="速度增量消耗">{{ serverMsg.showText.usStatus.Maneuver_deltaV_norm
          }}</el-descriptions-item>
      </el-descriptions>
    </div>
    <div class="wfWeixinWarnMsg" v-show="switches.showUsWarningDiv">
      <div style="color: #6adae8; font-size: medium; text-align: center; padding-top: 5px">我方卫星告警信息</div>
      <el-descriptions :column="2" style="font-size: small; margin-bottom: 5px">
        <el-descriptions-item label="告警信息">{{ serverMsg.showText.usWarning.Alarm_information }}</el-descriptions-item>
        <el-descriptions-item label="溯源方位角">{{ serverMsg.showText.usWarning.Yaw_angle }}</el-descriptions-item>
        <el-descriptions-item label="溯源方位角速度">{{ serverMsg.showText.usWarning.Yaw_angle_velocity
          }}</el-descriptions-item>
        <el-descriptions-item label="溯源俯仰角">{{ serverMsg.showText.usWarning.Pitch_angle }}</el-descriptions-item>
        <el-descriptions-item label="溯源俯仰角速度">{{ serverMsg.showText.usWarning.Pitch_angle_velocity
          }}</el-descriptions-item>
        <el-descriptions-item label="溯源距离">{{ serverMsg.showText.usWarning.Relative_position }}</el-descriptions-item>
        <el-descriptions-item label="溯源速度">{{ serverMsg.showText.usWarning.Relative_velocity }}</el-descriptions-item>
        <el-descriptions-item label="被打击状态">{{ serverMsg.showText.usWarning.Strike_state }}</el-descriptions-item>
        <el-descriptions-item label="被打击时长">{{ serverMsg.showText.usWarning.Accumulated_Strike_time
          }}</el-descriptions-item>
        <el-descriptions-item label="被打击部件">{{ serverMsg.showText.usWarning.Affected_components
          }}</el-descriptions-item>
        <el-descriptions-item label="到靶功率">{{ serverMsg.showText.usWarning.Target_power }}</el-descriptions-item>
        <el-descriptions-item label="部件完整度">{{ serverMsg.showText.usWarning.Integrity }}</el-descriptions-item>
        <el-descriptions-item label="告警级别">{{ serverMsg.showText.usWarning.Threat_level }}</el-descriptions-item>
        <el-descriptions-item label="目标意图">{{ serverMsg.showText.usWarning.Behavior_intention
          }}</el-descriptions-item>
        <el-descriptions-item label="光照角">{{ serverMsg.showText.usWarning.Sun_angle }}</el-descriptions-item>
        <el-descriptions-item label="打击开始时间">{{ serverMsg.showText.usWarning.strike_start_time
          }}</el-descriptions-item>
        <el-descriptions-item label="打击结束时间">{{ serverMsg.showText.usWarning.strike_end_time }}</el-descriptions-item>
      </el-descriptions>
    </div>
    <time-line v-show="switches.showTimeLineDiv" :time-lint-date="this.timeLineData"/>

  </div>
  <div>
    <div class="timeLineDiv" title="时间轴" @click="switches.showTimeLineDiv = !switches.showTimeLineDiv">
      <img src="img/icon/pinduan.png" class="imgItemClass"/>
    </div>
    <div class="enemySattleInfoDiv" title="敌方卫星状态信息"
         @click="switches.showEnemyStatus = !switches.showEnemyStatus">
      <img src="img/icon/img_1.png" class="imgItemClass"/>
    </div>
    <div class="enemyFigthDiv" title="敌方卫星作战效果"
         @click="switches.showEnemyFigthDiv = !switches.showEnemyFigthDiv">
      <img src="img/icon/img_1.png" class="imgItemClass"/>
    </div>
    <div class="usWarningDiv" title="我方卫星告警信息" @click="switches.showUsWarningDiv = !switches.showUsWarningDiv">
      <img src="img/icon/img_2.png" class="imgItemClass"/>
    </div>
    <div class="usSattleInfoDiv" title="我方卫星状态信息"
         @click="switches.showUsSattleInfoDiv = !switches.showUsSattleInfoDiv">
      <img src="img/icon/img_2.png" class="imgItemClass"/>
    </div>
    <div class="switchButtonDiv" title="控制台" @click="switches.showSwitchButtonDiv = !switches.showSwitchButtonDiv">
      <img src="img/icon/img.png" class="imgItemClass"/>
    </div>
    <div class="mars3dContainerMiniDiv" title="我方侦查敌方"
         @click="switches.showMiniContainerToEnemyDiv = !switches.showMiniContainerToEnemyDiv">
      <img src="img/icon/卫星云图.png" class="imgItemClass"/>
    </div>
    <div class="mars3dContainerMini1Div" title="敌方侦查我方"
         @click="switches.showMiniContainerToUsDiv = !switches.showMiniContainerToUsDiv">
      <img src="img/icon/卫星云图(红色).png" class="imgItemClass"/>
    </div>
  </div>
  <div id="credit"></div>
  <div
      :id="id"
      ref="cesiumContainer"
      style="width: 100%; height: 100%"
  />
</template>

<script>
import 'cesium/Build/Cesium/Widgets/widgets.css'
import * as Cesium from 'cesium'
// import {Viewer} from 'cesium'
import HeaderComp from '../part/HeaderComp.vue'
import {SatelliteScan,} from "@/components/utils/SatelliteScan";
// import {SatelliteScan,} from "@/components/utils/SattleCon";
import MiniContainerToEnemy from "@/components/views/miniContainerToEnemy.vue"
import MiniContainerToUs from "@/components/views/miniContainerToUs.vue";
import TimeLine from "@/components/views/timeLine.vue";
import {RealTimePathManager} from "@/components/utils/SatellitePath";
let viewer;

export default {
  name: 'CesiumMap',
  props: {
    id: {
      type: String,
      default: (() => Math.random().toString(36).substr(2))()
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '100%'
    }
  },
  components: {
    HeaderComp,
    MiniContainerToEnemy,
    MiniContainerToUs,
    TimeLine,
  },
  data() {
    return {
      //轨迹管理器
      pathManager: null,
      //是否初始化，为了防止地平线驱动无法初始化
      initCompleted: false,
      rate: undefined,
      isAvoid: false,
      messageData: {},
      //敌方卫星视线锥、夹角（为了判断角度是否有变化）
      enemyCone : null,
      enemyConeAngle : null,
      //我方卫星视线锥、夹角（为了判断角度是否有变化）
      usCone : null,
      usConeAngle : null,
      //导弹视线锥、夹角（为了判断角度是否有变化）
      missileCone : null,
      missileConeAngle : null,
      //敌方卫星射频波
      enemyWave : [],
      //我方卫星射频波
      usWave : [],
      //我方射频压制
      usDisturbWave : null,
      //我方射频锥颜色集合
      colorList : [
       '#00FF00FF','#ff0000','#0000FFFF','#FFFF00FF',
      '#00FFFFFF','#FF00FFFF','#e59324'],
      jgLine : null,
      jgDisturbLine : null,
      cameraType: '自由视角',
      timeLineData:[],
      usStaType : 1,
      enemyStaType : 1,
      id: undefined,
      switches: {
        showDetail: true,
        showOrbit: true,
        showCone: true,
        showName: true,
        showPoint: false,
        showModel: true,
        showTimeLineDiv: false,
        showEnemyStatus: false,
        showEnemyFigthDiv: false,
        showUsWarningDiv: false,
        showUsSattleInfoDiv: false,
        showSwitchButtonDiv: false,
        showMiniContainerToEnemyDiv: false,
        showMiniContainerToUsDiv: false,
      },
      // viewer: null,
      serverMsg: {
        timestamp: undefined,
        rate: undefined,
        stageName: undefined,
        taskCode: undefined,
        taskType: undefined,
        situation: undefined,
        showText: {
          enemyStatus: {},
          enemyFigth: {},
          usStatus: {},
          usWarning: {}
        }
      },
    }
  },
  created() {
    var params = this.getParams()
    this.id = params.get("taskId");
    this.initWebSocket();
  },
  unmounted() {
    this.websocket.onclose = this.websocketclose();
  },
  mounted() {
    this.initCesium()
  },
  beforeUnmount() {
    if (viewer) {
      viewer.destroy()
      viewer = null
    }
  },

  methods: {
    initSatelliteEntity(id, staType) {
      // 创建空的SampledPositionProperty（保持你现有的逻辑）
      const positionProperty = new Cesium.SampledPositionProperty();

      const entity = viewer.entities.add({
        id: id,
        position: positionProperty,
        model: {
          uri: staType === 1 ? '/model/weixin.gltf' :'/model/calipso/scene.gltf',
          scale: staType === 1 ? 40 : 10,
          minimumPixelSize: staType === 1 ? 80 : 50,
        },
        //轨迹
        // path: {
        //   // silhouetteSize: 1,
        //   // silhouetteColor: Cesium.Color.WHITE
        //   material: new Cesium.PolylineGlowMaterialProperty({
        //     glowPower: 0.2,
        //     color: new Cesium.Color.fromCssColorString('#00FF00FF'),
        //   }),
        //   width: 5,
        //   resolution: 1, // 降低分辨率可能提高稳定性
        //   leadTime: Number.POSITIVE_INFINITY,
        //   // trailTime: Number.POSITIVE_INFINITY
        //   trailTime: 3000
        // },
      });
      // 注册到路径管理器
      this.pathManager.registerEntity(id, positionProperty);

      return entity;
    },
    initMissileEntity(id) {
      // 创建空的SampledPositionProperty
      const positionProperty = new Cesium.SampledPositionProperty();
      const entity = viewer.entities.add({
        id: id,
        position: positionProperty,
        // orientation: new Cesium.VelocityOrientationProperty(position),
        model: {
          uri: '/model/df.glb',
          scale: 50,
          minimumPixelSize: 50,
          silhouetteSize: 1,
          silhouetteColor: Cesium.Color.WHITE
        },
        //轨迹
        // path: {
        //   material: new Cesium.PolylineGlowMaterialProperty({
        //     glowPower: 0.2,
        //     color: new Cesium.Color.fromCssColorString('#ff0000'),
        //   }),
        //   width: 5,
        //   leadTime: Number.POSITIVE_INFINITY,
        //   trailTime: Number.POSITIVE_INFINITY
        // }
      });
      // 注册到路径管理器
      this.pathManager.registerEntity(id, positionProperty);
      return entity;
    },

    //初始化Cesium
    initCesium() {
      // let key =
      //   "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI3NmYzMzU2MC0xY2EyLTQ4NWUtODQ0Yy00MDRiZTQ3NGQ1YTEiLCJpZCI6MzM3NzYxLCJpYXQiOjE3NTY4NjgyNzF9.ctKm4VzAAKZU22aIRbAUs6DBwQHDfmuAoCcDvZIXnas";
      // Cesium.Ion.defaultAccessToken = key;
      //AccessToken已在main.js中赋值
      const el = this.$refs.cesiumContainer
      viewer = new Cesium.Viewer(el, {
        selectionIndicator: false,
        infoBox: false,
        contextOptions: {
          // 硬件反走样，默认值为 1
          msaaLevel: 8,
          requestWebgl2: true
        },
        animation: true,  //时钟
        timeline: true, // 底部时间线
        fullscreenButton: true, // 全屏
        vrButton: false, // VR
        sceneModePicker: false, // 选择视角的模式（球体、平铺、斜视平铺）
        baseLayerPicker: false, // 图层选择器（地形影像服务）
        navigationHelpButton: false, // 导航帮助(手势，鼠标)
        geocoder: true, // 位置查找工具
        homeButton: true,// 视角返回初始位置
        shadows: false,//阴影  未生效？
        terrainShadows: false,//阴影  未生效？
        creditContainer: "credit",
        scene3DOnly: true,
        // skyBox: false,       // 完全关闭默认星空
        // skyAtmosphere: false, // 关闭大气散射效果
        maximumRenderTimeChange: Infinity,
        // shouldAnimate: true,  // 必须启用！
        // clockViewModel: new Cesium.ClockViewModel(viewer.clock)
      })



      //地球坐标轴
      // viewer.scene.primitives.add(new Cesium.DebugModelMatrixPrimitive({
      //   length: 20000000,
      //   width: 2
      // }))
      //调试面板
      // viewer.extend(Cesium.viewerCesiumInspectorMixin)
      // viewer.scene.globe.imageBasedLightingFactor = new Cesium.Cartesian2(1.0, 1.0);
      // // 调整光源设置
      // viewer.scene.light = new Cesium.DirectionalLight({
        // direction: new Cesium.Cartesian3(0.5, -0.5, -1.0), // 调整光源方向
        // intensity: 10.0 // 增加光源强度
      // });
// 关闭Cesium的自动坐标系旋转（关键！）
      viewer.scene.preloadFrame = true;

      window.viewer = viewer;
// 在这里初始化路径管理器
       this.pathManager = new RealTimePathManager();
    },

    //初始化webscoket连接
    initWebSocket() {
      // 创建链接
      this.websocket = new WebSocket('ws://127.0.0.1:10808/webSocketServer/' + this.id);
      // this.websocket = new WebSocket('ws://101.42.25.54:10808/webSocketServer/' + this.id);
      var that = this.websocket;
      that.onopen = this.websocketonopen;
      that.onerror = this.websocketonerror;
      that.onmessage = this.websocketonmessage;
      that.onclose = this.websocketclose;
    },
    //获取url参数
    getParams() {
      return new URLSearchParams(window.location.search)
    },
    //关闭webscoket连接
    websocketclose(e) {
      console.log("connection closed (" + e.code + ")");
    },

    //数据接收
    websocketonmessage(e) {
      //处理逻辑
      if (e.data === '' || e.data === 'ok' || e.data === 'error' || e.data == null) {
        return;
      }
      // console.log("收到服务端消息：" + e.data)
      const timeString = JSON.parse(e.data).timestamp + (JSON.parse(e.data).timestamp.endsWith('Z') ? '' : 'Z');
      const usSatellite = JSON.parse(e.data).situation.usSatellite;
      const enemySatellite = JSON.parse(e.data).situation.enemySatellite;
      const missileParam = JSON.parse(e.data).situation.missileParam;
      const usRfParam = JSON.parse(e.data).situation.usRfParam;
      const enemyRfParam = JSON.parse(e.data).situation.enemyRfParam;
      const jgParam = JSON.parse(e.data).situation.jgParam;
      const jgDisturbParam = JSON.parse(e.data).situation.jgDisturbParam;
      const rfDisturbParam = JSON.parse(e.data).situation.rfDisturbParam;
      // const usGraphicByAttr = wxLayer.getGraphicById('weixinA')
      // const enemyGraphicByAttr = wxLayer.getGraphicById('weixinB')
      // const missileGraphicById = wxLayer.getGraphicById('missile')
      // const missileSatelliteSensorGraphicById = wxLayer.getGraphicById('missileSatelliteSensor')
      // const usGraphicByAttrM = wxLayerM.getGraphicByAttr('我方卫星M', 'name')
      // const enemyGraphicByAttrM = wxLayerM.getGraphicByAttr('敌方卫星M', 'name')
      const stageName = JSON.parse(e.data).stageName;
      // viewer.entities.getById('weixing').position = Cesium.Cartesian3.fromDegrees(usSatellite.longitude, usSatellite.latitude, usSatellite.altitude);
      const time = Cesium.JulianDate.fromIso8601(timeString);

      this.messageData = JSON.parse(e.data)
      this.serverMsg.taskType = JSON.parse(e.data).taskType
      this.serverMsg.timestamp = JSON.parse(e.data).timestamp
      this.serverMsg.rate = JSON.parse(e.data).rate
      this.serverMsg.stageName = JSON.parse(e.data).stageName
      this.serverMsg.taskCode = JSON.parse(e.data).taskCode
      this.serverMsg.showText.enemyFigth = JSON.parse(e.data).showText.enemyFigth
      this.serverMsg.showText.enemyStatus = JSON.parse(e.data).showText.enemyStatus
      this.serverMsg.showText.usStatus = JSON.parse(e.data).showText.usStatus
      this.serverMsg.showText.usFigth = JSON.parse(e.data).showText.usFigth
      this.serverMsg.showText.usWarning = JSON.parse(e.data).showText.usWarning ? JSON.parse(e.data).showText.usWarning : {}
      this.timeLineData = JSON.parse(e.data).timeLineData
      this.usStaType = JSON.parse(e.data).usStaType
      this.enemyStaType = JSON.parse(e.data).enemyStaType
      if (this.rate === undefined){
        this.rate = JSON.parse(e.data).rate
      }
      if (!this.initCompleted) {
        // 初始化时钟（以当前点为中心前后扩展）
        // viewer.clock.startTime = Cesium.JulianDate.addHours(time, -1, new Cesium.JulianDate());
        viewer.clock.startTime = time.clone();
        viewer.clock.stopTime = Cesium.JulianDate.addHours(time, 2, new Cesium.JulianDate());
        viewer.clock.currentTime = time.clone();
        viewer.clock.clockRange = Cesium.ClockRange.UNBOUNDED;
        viewer.clock.multiplier = 1;

        this.initSatelliteEntity('enemyweixing',this.enemyStaType);
        this.initSatelliteEntity('usweixing',this.usStaType);
        this.initCompleted = true;
        console.log("初始化主页面时钟、实体设置完成");

      } else {
        viewer.clock.currentTime = time.clone();
       // 动态扩展时间轴
        if (Cesium.JulianDate.compare(time, viewer.clock.stopTime) > 0) {
          viewer.clock.stopTime = Cesium.JulianDate.addHours(time, 1, new Cesium.JulianDate());
        }
      }


      const enemyweixingentity = viewer.entities.getById('enemyweixing');
      const usweixingentity = viewer.entities.getById('usweixing');
      let missileEntity = viewer.entities.getById('missileweixing');



      //1、更新敌方卫星位置、姿态、视线锥
      this.updateEnemySatellite(enemyweixingentity, enemySatellite, enemyRfParam,jgParam, time)
      //2、更新我方卫星位置、姿态、视线锥
      this.updateUsSatellite(usweixingentity, usSatellite, usRfParam,jgDisturbParam,rfDisturbParam,time)
      //3、更新导弹位置、姿态
      this.updateMissile(missileEntity, missileParam, time)



    },


    updateEnemySatellite(enemyweixingentity, enemySatellite, enemyRfParam,jgParam, time) {
      //敌方卫星:位置、姿态
      enemyweixingentity.position.addSample(time, Cesium.Cartesian3.fromDegrees(enemySatellite.longitude, enemySatellite.latitude, enemySatellite.altitude));
      enemyweixingentity.position._value = Cesium.Cartesian3.fromDegrees(enemySatellite.longitude, enemySatellite.latitude, enemySatellite.altitude)
      const roll = this.enemyStaType === 1 ? enemySatellite.roll :  enemySatellite.roll + 180
      let r2 = new Cesium.HeadingPitchRoll(Cesium.Math.toRadians(enemySatellite.direction  ), Cesium.Math.toRadians(enemySatellite.pitch), Cesium.Math.toRadians(roll))
      enemyweixingentity.orientation = Cesium.Transforms.headingPitchRollQuaternion(enemyweixingentity.position._value, r2)
      //视椎体
      if (enemySatellite.angle !== '0' && enemySatellite.angle !== 0 && enemySatellite.axisLength !== 0 && enemySatellite.axisLength !== '0' ){
        console.log('敌方卫星视椎体')
        this.enemyCone = this.createOrUpdateCone(enemyweixingentity, enemySatellite, this.enemyCone,'#0fa2e1','enemy')
      }
      //射频波束
      if (Object.keys(enemyRfParam).length > 0  && enemyRfParam.length !== 0){
        this.enemyWave = this.createOrUpdateWave(enemyweixingentity, enemySatellite, enemyRfParam, this.enemyWave,this.colorList)
      }

      //****射频场景参数是字符串******抵近场景无此参数****
      if (jgParam && typeof jgParam.length === 'string'){
        jgParam.length = parseInt(jgParam.length)
      }
      if (jgParam && Object.keys(jgParam).length > 0 &&  jgParam.length !== 0){
        this.jgLine = this.createOrUpdateJgLine(enemyweixingentity,this.enemyStaType,jgParam.length, this.jgLine)
      }else if (this.jgLine != null){
        console.log('jgLine不显示')
        this.jgLine.show = false
      }
    },
    updateUsSatellite(usweixingentity, usSatellite,usRfParam,jgDisturbParam,rfDisturbParam, time) {
      //我方卫星:位置、姿态
      usweixingentity.position.addSample(time, Cesium.Cartesian3.fromDegrees(usSatellite.longitude, usSatellite.latitude, usSatellite.altitude));
      usweixingentity.position._value = Cesium.Cartesian3.fromDegrees(usSatellite.longitude, usSatellite.latitude, usSatellite.altitude)
      // enemyweixingentity.orientation =  new Cesium.VelocityOrientationProperty( enemyweixingentity.position);
      const roll = this.usStaType === 1 ? usSatellite.roll :  usSatellite.roll + 180
      let r3 = new Cesium.HeadingPitchRoll(Cesium.Math.toRadians(usSatellite.direction), Cesium.Math.toRadians(usSatellite.pitch), Cesium.Math.toRadians(roll))
      usweixingentity.orientation = Cesium.Transforms.headingPitchRollQuaternion(usweixingentity.position._value, r3)
      //视椎体
      if (usSatellite.angle !== '0' && usSatellite.axisLength !== 0) {
        this.usCone = this.createOrUpdateCone(usweixingentity, usSatellite, this.usCone, '#0fa2e1','us')
      }
      //射频波束
      if (usRfParam && Object.keys(usRfParam).length > 0  && usRfParam.length !== 0){
        this.usWave = this.createOrUpdateWave(usweixingentity, usSatellite, usRfParam, this.usWave,this.colorList)
      }
      //射频反制
      if (rfDisturbParam && Object.keys(rfDisturbParam).length > 0 && rfDisturbParam.RF_counterattack_distance !== 0 && rfDisturbParam.RF_beam_divergence_angle !== 0){
        this.usDisturbWave = this.createOrUpdateDisturbWave(usweixingentity, usSatellite, rfDisturbParam, this.usDisturbWave,this.colorList)
      }else if (this.usDisturbWave != null){
        console.log('usDisturbWave不显示')
        this.usDisturbWave.show = false
      }
      //激光反制
      if(jgDisturbParam && Object.keys(jgDisturbParam).length > 0  && jgDisturbParam.Laser_counterattack_distance !== 0 && jgDisturbParam.Laser_beam_divergence_angle !== 0){
       this.jgDisturbLine = this.createOrUpdateJgLine(usweixingentity,this.usStaType,jgDisturbParam.Laser_counterattack_distance, this.jgDisturbLine)
      }else if (this.jgDisturbLine != null){
        console.log('jgDisturbLine不显示')
        this.jgDisturbLine.show = false
      }
    },
    updateMissile(missileEntity, missileParam, time) {
      //导弹：初始化、位置、姿态
      if (!missileParam || !Object.keys(missileParam).length > 0 || missileParam.longitude === '0' || missileParam.latitude === '0') {
        return
      }
        if (missileEntity == null) {
          missileEntity = this.initMissileEntity('missileweixing');
        }
        missileEntity.position.addSample(time, Cesium.Cartesian3.fromDegrees(missileParam.longitude, missileParam.latitude, missileParam.altitude));
       missileEntity.position._value = Cesium.Cartesian3.fromDegrees(missileParam.longitude, missileParam.latitude, missileParam.altitude)
        //导弹姿态，这样能改变，但改变的方向好像不对
        // missileEntity.orientation = new Cesium.VelocityOrientationProperty(missileEntity.position);
        let r3 = new Cesium.HeadingPitchRoll(Cesium.Math.toRadians(missileParam.direction), Cesium.Math.toRadians(missileParam.pitch), Cesium.Math.toRadians(missileParam.roll))
        missileEntity.orientation = Cesium.Transforms.headingPitchRollQuaternion(missileEntity.position._value, r3)
      //视椎体
    if (missileParam.angle !== '0' && missileParam.axisLength !== 0){
      this.missileCone =  this.createOrUpdateCone(missileEntity, missileParam, this.missileCone,'#ce1023','missile')
    }

    },
    //射频波束
    createOrUpdateWave(entity, satelliteParam,rfParam, wave, color){
      if (!Array.isArray(rfParam.semiapexAngle)){
        rfParam.semiapexAngle = [rfParam.semiapexAngle]
      }
      if (wave.length  !== 0) {
        // satelliteScanInstance.orientation = Cesium.Transforms.headingPitchRollQuaternion(enemyweixingentity.position._value, r2)
        // 计算旋转角(弧度)
        let hpr = Cesium.HeadingPitchRoll.fromDegrees(satelliteParam.direction, satelliteParam.pitch, satelliteParam.roll);
        //移动位置
        let origin =entity.position._value;
        let matrix = Cesium.Transforms.headingPitchRollToFixedFrame(origin, hpr);
        const offset = new Cesium.Cartesian3(0, 0, 0.5 * rfParam.length);
        Cesium.Matrix4.multiplyByTranslation(matrix, offset, matrix);
        for (let i = 0; i < wave.length; i++){
          wave[i].updateMatrix(matrix);
          // console.log("射频波束更新" + i)
        }
        // viewer.camera.lookAt(origin, new Cesium.HeadingPitchRange(hpr.heading, hpr.pitch, 10000000));
        // viewer.camera.flyTo( { destination: origin})
      }else {
        for (let i = 0; i < rfParam.semiapexAngle.length; i++) {
         let waveItem = new SatelliteScan({
            radius: rfParam.length * Math.tan(Cesium.Math.toRadians(rfParam.semiapexAngle[i])),
            color: new Cesium.Color.fromCssColorString(color[i]).withAlpha(0.4),
            path: entity,
            inverse: false,
            slices: 20,
            thickness: 0.5,
            lenght: rfParam.length,
          });
          waveItem.addTo(viewer);
          wave.push(waveItem)
          // console.log('射频波束添加成功')
        }

      }
      return wave
    },
    //射频反制波束
    createOrUpdateDisturbWave(entity, satelliteParam,rfDisturbParam, disturbWave, color){

      if (disturbWave  !== null) {
        // satelliteScanInstance.orientation = Cesium.Transforms.headingPitchRollQuaternion(enemyweixingentity.position._value, r2)
        // 计算旋转角(弧度)
        let hpr = Cesium.HeadingPitchRoll.fromDegrees(rfDisturbParam.direction_RF, rfDisturbParam.pitch_RF, rfDisturbParam.roll_RF);
        //移动位置
        let origin =entity.position._value;
        let matrix = Cesium.Transforms.headingPitchRollToFixedFrame(origin, hpr);
        const offset = new Cesium.Cartesian3(0, 0, 0.5 * rfDisturbParam.RF_counterattack_distance);
        Cesium.Matrix4.multiplyByTranslation(matrix, offset, matrix);
        disturbWave.updateMatrix(matrix);
          console.log("射频压制波束更新")
        // viewer.camera.lookAt(origin, new Cesium.HeadingPitchRange(hpr.heading, hpr.pitch, 10000000));
        // viewer.camera.flyTo( { destination: origin})
      }else {
        disturbWave = new SatelliteScan({
            radius: rfDisturbParam.RF_counterattack_distance * Math.tan(Cesium.Math.toRadians(rfDisturbParam.RF_beam_divergence_angle)),
            color: new Cesium.Color.fromCssColorString(color[1]).withAlpha(0.4),
            path: entity,
            inverse: false,
            slices: 20,
            thickness: 0.5,
            lenght: rfDisturbParam.RF_counterattack_distance,
          });
        disturbWave.addTo(viewer);
          // wave.push(waveItem)
          console.log('射频压制波束添加成功')
      }
      return disturbWave
    },
    //视椎体
    createOrUpdateCone (entity, satelliteParam, cone, color,type){
      const angle = type === 'us' ? this.usConeAngle : type === 'enemy' ? this.enemyConeAngle : this.missileConeAngle
      if (angle && angle !== satelliteParam.angle && cone !== null && cone.primitive !== null){
        // console.log("qian-视椎体存在:" + viewer.scene.primitives.contains(cone.primitive))
        cone.primitive.show = false
        // cone.removeFrom( viewer)
        // cone.primitive.remove()
        // console.log("销毁:", cone.primitive.isDestroyed())
        // console.log("hou-视椎体存在:" + viewer.scene.primitives.contains(cone.primitive))
        // cone.primitive.remove()
        //   console.log("销毁后:", viewer.scene.primitives.contains(cone.primitive));
          cone = null;
        console.log("视椎体夹角更新:" + angle + "->" + satelliteParam.angle)
        if (this.serverMsg.stageName === 'ATP精跟踪' && type === 'enemy'){
          color = '#1bf503'
        }
      }
      if (cone !== null ) {
        console.log("视椎体更新")
        // satelliteScanInstance.orientation = Cesium.Transforms.headingPitchRollQuaternion(enemyweixingentity.position._value, r2)
        // 计算旋转角(弧度)
        let hpr = Cesium.HeadingPitchRoll.fromDegrees(satelliteParam.direction, satelliteParam.pitch, satelliteParam.roll);
        //移动位置
        let origin =entity.position._value;
        let matrix = Cesium.Transforms.headingPitchRollToFixedFrame(origin, hpr);
        const offset = new Cesium.Cartesian3(0, 0, 0.5 * Number(satelliteParam.axisLength));
        Cesium.Matrix4.multiplyByTranslation(matrix, offset, matrix);
        cone.updateMatrix(matrix)
        // viewer.camera.lookAt(origin, new Cesium.HeadingPitchRange(hpr.heading, hpr.pitch, 10000000));
        // viewer.camera.flyTo( { destination: origin})
      }else {
        this.enemyConeAngle = satelliteParam.angle
        cone = new SatelliteScan({
          radius: Number(satelliteParam.axisLength) * Math.tan(Cesium.Math.toRadians(satelliteParam.angle)),
          color: new Cesium.Color.fromCssColorString(color).withAlpha(0.3),
          path: entity,
          inverse: false,
          slices: 20,
          thickness: 1,
          lenght:  satelliteParam.axisLength,
        });
        console.log('卫星视椎体添加成功')
        cone.addTo(viewer);
        // viewer.scene.primitives.add(cone.primitive.primitive);
        // console.log('敌方卫星视椎体添加成功')
      }
      return cone
    },
    removePrimitiveByReference(primitive) {
      for (let i = viewer.scene.primitives.length - 1; i >= 0; i--) {
        const p = viewer.scene.primitives.get(i);
        if (p === primitive) {
          viewer.scene.primitives.remove(p);
          console.log("通过索引移除成功，索引:", i);
          return true;
        }
      }
      console.log("未找到对应的primitive");
      return false;
    },
    //激光
    createOrUpdateJgLine(entity,staType, length, jgLine) {
      // 计算激光终点坐标的函数
      const calculateEndPosition = (time) => {
        // 获取卫星实体的当前位置和方向
        const startPosition = entity.position.getValue(time);

        // 获取entity的朝向（旋转矩阵）
        const orientation = entity.orientation.getValue(time);
        const rotationMatrix = Cesium.Matrix3.fromQuaternion(orientation);

        // 定义Z轴方向向量（在entity局部坐标系中）
        // const localZAxis = new Cesium.Cartesian3(0, 0, 1);
        const localZAxis = staType === 1 ? new Cesium.Cartesian3(0, 0, 1) : new Cesium.Cartesian3(0, 0, -1)

        // 将局部Z轴方向转换到世界坐标系
        const worldZAxis = Cesium.Matrix3.multiplyByVector(
            rotationMatrix,
            localZAxis,
            new Cesium.Cartesian3()
        );

        // 归一化方向向量
        Cesium.Cartesian3.normalize(worldZAxis, worldZAxis);


        // 沿Z轴方向延伸指定长度
        const direction = Cesium.Cartesian3.multiplyByScalar(
            worldZAxis,
            length,
            new Cesium.Cartesian3()
        );

        // 计算终点位置
        return Cesium.Cartesian3.add(startPosition, direction, new Cesium.Cartesian3());
      };

      if (jgLine !== null) {
        // 更新现有激光线
        jgLine.polyline.positions = new Cesium.CallbackProperty((time) => {
          const start = entity.position.getValue(time);
          const end = calculateEndPosition(time);
          return [start, end];
        }, false);
        // console.log("激光线更新（平滑版本）:"+ jgLine);
        return jgLine;
      } else {
        // 创建新激光线
        jgLine = viewer.entities.add({
          polyline: {
            positions: new Cesium.CallbackProperty((time) => {
              const start = entity.position.getValue(time);
              const end = calculateEndPosition(time);
              return [start, end];
            }, false),
            width: 10,
            arcType: Cesium.ArcType.NONE,
            material: new Cesium.PolylineGlowMaterialProperty({
              glowPower: 0.4,
              color: Cesium.Color.RED,
              taperPower: 1
            }),
          }
        });
        // console.log('激光线添加成功（平滑版本）:' + jgLine);
        return jgLine;
      }
    },
    changeCameraType(val) {
      if (val === '自由视角') {
        viewer.trackedEntity = null;
        viewer.camera.flyHome(2)

      } else if (val === '我方卫星') {
        viewer.trackedEntity = viewer.entities.getById('usweixing');

      }else if (val === '敌方卫星') {
        viewer.trackedEntity = viewer.entities.getById('enemyweixing');

      }else if (val === '导弹'){
        viewer.trackedEntity = viewer.entities.getById('missileweixing');

      }else {
        viewer.trackedEntity = null;
        viewer.camera.flyHome(2)
      }
    },
    handleChangeRate(val) {
      const params = this.getParams()
      const taskId = params.get('taskId')
      const reqMsg = {
        taskId: taskId,
        rate: val
      }
      if (this.websocket.readyState === WebSocket.OPEN) {
        this.websocket.send(JSON.stringify(reqMsg))
        console.log('WebSocket连接成功')
      } else {
        console.log('WebSocket连接失败')
      }
    },
    avoid(val) {
      const params = this.getParams()
      const taskId = params.get('taskId')
      const reqMsg = {
        taskId: taskId,
        eludeFlag: val
      }
      if (this.websocket.readyState === WebSocket.OPEN) {
        this.websocket.send(JSON.stringify(reqMsg))
        console.log('WebSocket连接成功')
      } else {
        console.log('WebSocket连接失败')
      }
    },









    }




  }

</script>
<style scoped>
.timeLineDiv {
  position: absolute;
  left: 10px;
  z-index: 100;
//bottom: 600px; top: 60%;
}

.enemySattleInfoDiv {
  position: absolute;
  left: 10px;
  z-index: 100;
//bottom: 500px; top: 40%;

}

.enemyFigthDiv {
  position: absolute;
  left: 10px;
  z-index: 100;
  bottom: 200px;
}

.usWarningDiv {
  position: absolute;
  right: 10px;
  z-index: 100;
//bottom: 500px; top: 40%;
}

.usSattleInfoDiv {
  position: absolute;
  right: 10px;
  z-index: 100;
//bottom: 200px; top: 70%;
}

.switchButtonDiv {
  position: absolute;
  left: 10px;
  z-index: 100;
//bottom: 750px; top: 10%;
}

.mars3dContainerMiniDiv {
  position: absolute;
  right: 10px;
  z-index: 100;
//bottom: 650px; top: 10%;
}

.mars3dContainerMini1Div {
  position: absolute;
  right: 10px;
  z-index: 100;
//bottom: 750px; top: 20%;
}

.imgItemClass {
  width: 42px;
  height: 42px;
  cursor: pointer;
}
.wfWeixinWarnMsg {
  position: absolute;
  top: 35%;
  right: 4%;
  width: 25%;
  height: 36%;
  border-radius: 20px;
  background-color: rgba(255, 165, 0, 0.2);
  color: #163b63;
  font-size: small;
  z-index: 100;
  border: orange 1px solid;
  /* el-descriptions中lable文本颜色 */
  --el-text-color-primary: #ffffff;
  /* el-descriptions中值的文本颜色 */
  --el-text-color-regular: #ffffff;
}
/* el-descriptions样式 必须这样写才是透明的 */
.wfWeixinWarnMsg :deep(.el-descriptions),
.wfWeixinWarnMsg :deep(.el-descriptions__body){
  background-color: transparent  !important;
  margin-left: 10px;
}
.wfWeixinStatus {
  position: absolute;
  top: 72%;
  right: 4%;
  width: 25%;
  height: 18%;
  border-radius: 20px;
  background-color: rgba(22, 59, 99, 0.5);
  color: #163b63;
  font-size: small;
  z-index: 100;
  border: #163b63 1px solid;
  /* el-descriptions中lable文本颜色 */
  --el-text-color-primary: #ffffff;
  /* el-descriptions中值的文本颜色 */
  --el-text-color-regular: #ffffff;
}
/* el-descriptions样式 必须这样写才是透明的 */
.wfWeixinStatus :deep(.el-descriptions),
.wfWeixinStatus :deep(.el-descriptions__body){
  background-color: transparent  !important;
  margin-left: 10px;
}
.switchButton {
  position: absolute;
  top: 8%;
  left: 4%;
  width: 32%;
  height: 22%;
  border-radius: 20px;
  background-color: rgba(22, 59, 99, 0.5);
  color: #6adae8;
  font-size: small;
  z-index: 99;
  border: #163b63 1px solid;
  /* el-descriptions中lable文本颜色 */
  --el-text-color-primary: #ffffff;
  /* el-descriptions中值的文本颜色 */
  --el-text-color-regular: #ffffff;

}
/* el-descriptions样式 必须这样写才是透明的 */
.switchButton :deep(.el-descriptions),
.switchButton :deep(.el-descriptions__body){
  background-color: transparent  !important;
  margin-left: 10px;
}
.targetSelect {
  width: 400px;
  height: 100px;
  position: absolute;
  top: 100px;
  left: 300px;
  z-index: 999;

}

/* 确保穿透 scoped 样式，并提高选择器优先级 */
.targetSelect :deep(.el-input-number) {
  /* 如果组件最外层 div 也有背景色，可以在这里设置透明 */
  background-color: transparent;
}
/* 2. 修改输入框部分的样式，关键可能是移除右侧边框 */
.targetSelect :deep(.el-input-number .el-input__wrapper) {
  background-color: #0d4a77 !important; /* 输入框背景透明 */
  box-shadow: none !important; /* 移除 Element Plus 默认的 box-shadow（可能模拟边框） */
  border: none !important; /* 确保无边框 */
}
.targetSelect :deep(.el-input-number .el-input__inner) {
  background-color: #0d4a77; /* 输入框内部背景透明 */
  color: white; /* 输入文字颜色 */
}
/* 1. 修改增减按钮的样式，确保背景透明且无边框 */
.targetSelect :deep(.el-input-number__increase),
.targetSelect :deep(.el-input-number__decrease) {
  background-color: #0d4a77 !important; /* 按钮背景透明 */
  border: none !important; /* 移除按钮边框 */
  color: white; /* 设置按钮图标颜色，与你环境匹配 */
}
.dfWeixinStatus {
  position: absolute;
  top: 43%;
  left: 4%;
  width: 31%;
  height: 18%;
  border-radius: 20px;
  background-color: rgba(255, 0, 0, 0.2);
  color: #e2e8e2;
  font-size: small;
  z-index: 100;
  border: red 1px solid;
  /* el-descriptions中lable文本颜色 */
  --el-text-color-primary: #ffffff;
  /* el-descriptions中值的文本颜色 */
  --el-text-color-regular: #ffffff;
}

/* el-descriptions样式 必须这样写才是透明的 */
.dfWeixinStatus :deep(.el-descriptions),
.dfWeixinStatus :deep(.el-descriptions__body){
  background-color: transparent  !important;
  margin-left: 10px;
}
.dfWeixinFigthStatus {
  position: absolute;
  top: 73%;
  left: 4%;
  width: 25%;
  height: 15%;
  border-radius: 20px;
  background-color: rgba(255, 0, 0, 0.2);
  color: #163b63;
  font-size: small;
  z-index: 100;
  border: red 1px solid;
  /* el-descriptions中lable文本颜色 */
  --el-text-color-primary: #ffffff;
  /* el-descriptions中值的文本颜色 */
  --el-text-color-regular: #ffffff;
}
/* el-descriptions样式 必须这样写才是透明的 */
.dfWeixinFigthStatus :deep(.el-descriptions),
.dfWeixinFigthStatus :deep(.el-descriptions__body){
  background-color: transparent  !important;
  margin-left: 10px;
}
</style>
